//
//  SuperCatHeaderView.swift
//  MySwiftPullToRefresh
//
//  Created by likai on 2017/5/8.
//  Copyright © 2017年 terry. All rights reserved.
//

import UIKit

class SuperCatHeaderView: RefreshHeaderView {

    private var refreshItems: [RefreshItem] = []
    private var signRefreshItem: RefreshItem!
    private var isSignVisible = false
    
    override func updateRefreshState(_ isRefreshing: Bool) {
        if isRefreshing {
            showSign(false)
            
            //猫 和 披风 动画
            let cape = refreshItems[5].view
            let cat = refreshItems[4].view
            
            cape.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 32)
            cat.transform = CGAffineTransform(translationX: 1.0, y: 0)
            
            UIView.animate(withDuration: 0.2, delay: 0, options: [.repeat, .autoreverse], animations: {
                
                cape.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 32)
                cat.transform = CGAffineTransform(translationX: -1.0, y: 0)
            }, completion: nil)
            
            //地面 和 建筑 动画
            let buildinds = refreshItems[0].view
            let ground = refreshItems[2].view
            
            
            UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: { 
            
                ground.center.y += self.height
                buildinds.center.y += self.height
            }, completion: nil)
        }else {
            let cape = refreshItems[5].view
            let cat = refreshItems[4].view
            cape.transform = .identity
            cat.transform = .identity
            cape.layer.removeAllAnimations()
            cat.layer.removeAllAnimations()
        }
    }
    
    override func updatePregress(_ pregress: CGFloat) {
        let value = pregress * 0.7 + 0.2
        backgroundColor = UIColor(red: value, green: value, blue: value, alpha: 1.0)
        
        refreshItems.forEach{ $0.updateViewPositionForPercentage(pregress)}
        
        showSign(pregress == 1)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        setupRefreshItems()
    }
    
    private func setupRefreshItems(){
        if !refreshItems.isEmpty {
            return
        }
        let bundle = Bundle(for: type(of: self))
        
        let groundImageView = UIImageView(image: UIImage(named: "ground", in: bundle, compatibleWith: nil))
        let buildingImageView = UIImageView(image: UIImage(named: "buildings", in: bundle, compatibleWith: nil))
        let sunImageView = UIImageView(image: UIImage(named: "sun", in: bundle, compatibleWith: nil))
        let catImageView = UIImageView(image: UIImage(named: "cat", in: bundle, compatibleWith: nil))
        let capeBackImageView = UIImageView(image: UIImage(named: "cape_back", in: bundle, compatibleWith: nil))
        let capeFrontImageView = UIImageView(image: UIImage(named: "cape_front", in: bundle, compatibleWith: nil))
        
        
        refreshItems = [
        RefreshItem(view: buildingImageView, centerEnd: CGPoint(x: bounds.midX, y: bounds.height - groundImageView.bounds.height - buildingImageView.bounds.midY), parallacRation: 1.5, sceneHeight: height),
        RefreshItem(view: sunImageView, centerEnd: CGPoint(x: bounds.width * 0.1, y: bounds.height - groundImageView.bounds.height - sunImageView.bounds.height), parallacRation: 3, sceneHeight: height),
        RefreshItem(view: groundImageView, centerEnd: CGPoint(x: bounds.midX, y: bounds.height - groundImageView.bounds.midY), parallacRation: 0.5, sceneHeight: height),
        RefreshItem(view: capeBackImageView, centerEnd: CGPoint(x: bounds.midX, y: bounds.height - groundImageView.bounds.midY - capeBackImageView.bounds.midY), parallacRation: -1, sceneHeight: height),
        RefreshItem(view: catImageView, centerEnd: CGPoint(x: bounds.midX, y: bounds.height - groundImageView.bounds.midY - catImageView.bounds.midY), parallacRation: 1, sceneHeight: height),
        RefreshItem(view: capeFrontImageView, centerEnd: CGPoint(x: bounds.midX, y: bounds.height - groundImageView.bounds.midY - capeFrontImageView.bounds.midY), parallacRation: -1, sceneHeight: height)
            
            
            
            
        ]
        
        refreshItems.forEach{ addSubview($0.view)}
        
        let signImageView = UIImageView(image: UIImage(named: "sign", in: bundle, compatibleWith: nil))
        signRefreshItem = RefreshItem(view: signImageView, centerEnd: CGPoint(x: bounds.midX, y: bounds.height - signImageView.bounds.midY), parallacRation: 0.5, sceneHeight: height)
        addSubview(signImageView)
    }
    
    
    private func showSign(_ show: Bool){
        if isSignVisible == show {
            return
        }
        isSignVisible = show
        
        UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseInOut, .beginFromCurrentState], animations: { 
            
            self.signRefreshItem.updateViewPositionForPercentage(show ? 1 : 0)
            
        }, completion: nil)
        
    }

}

private final class RefreshItem{
    private var centerStart: CGPoint
    private var centerEnd:CGPoint
    //unowned:相当于__unsafe_unretained, 不安全. 必须为非可选类型
    /*
    //unowned引用是non-zeroing(非零的), 在ARC销毁内存后，不会被赋为nil, 这表示着当一个对象被销毁时, 它指引的对象不会清零. 也就是说使用unowned引用在某些情况下可能导致dangling pointers(野指针). 所以在访问无主引用的时候，要确保其引用正确，不然会引起内存崩溃.
    
    */
    unowned var view:UIView
    
    init(view:UIView, centerEnd:CGPoint, parallacRation: CGFloat, sceneHeight:CGFloat){
        self.view = view
        self.centerEnd = centerEnd
        centerStart = CGPoint(x: centerEnd.x, y: centerEnd.y + (parallacRation * sceneHeight))
        self.view.center = centerStart
    }
    
    func updateViewPositionForPercentage(_ percentage : CGFloat){
        view.center = CGPoint(x: centerStart.x + (centerEnd.x - centerStart.x) * percentage, y: centerStart.y + (centerEnd.y - centerStart.y) * percentage)
        
    }
}
